package com.wandian.news.mvvm.challenge;

import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.config.CoinTypeEnum;
import com.mylib.libcore.config.RouterConfig;
import com.mylib.libcore.mvvm.BaseMVVMActivity;
import com.mylib.libcore.tools.CSJADTools;
import com.mylib.libcore.tools.GDTADTools;
import com.mylib.libcore.tools.TTAdManagerHolder;
import com.mylib.libcore.utils.ActivityUtil;
import com.mylib.libcore.utils.ToastUtil;
import com.mylib.libcore.utils.UIUtils;
import com.mylib.widget.CustomCoinToast;
import com.wandian.news.R;
import com.wandian.news.databinding.NewsActivityChallengeBinding;
import com.wandian.news.dialog.ChallengeResultDialog;

import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;
import com.yilan.sdk.ui.web.WebActivity;

import static com.mylib.libcore.config.AppConfig.CSJ_BANNER_ONE_ID;
import static com.mylib.libcore.config.NewsApiConfig.NEWS_KNOWLEDGE_WORK_PD;
import static com.mylib.libcore.config.NewsApiConfig.NEWS_KNOWLEDGE_WORK_WD;

/**
 * @author Administrator
 * @date 2019/12/18-14:28
 * @description 挑战activity
 **/
@Route(path = RouterConfig.ROUTER_ACTIVITY_NEWS_CHALLENGE)
public class ChallengeActivity extends BaseMVVMActivity<ChallengeViewModel> implements ChallengeResultDialog.ChallengeDialogBtnClink{
    private NewsActivityChallengeBinding dataBinding;
    private ChallengeResultDialog challengeResultDialog;

    private String xztSelectText = "";
    private String pdtSelect = "";
    private String pdtAnswer = "";
    private int challengeNumber = 0;
    private int nowZL = 0;
    private String reason ="";
    private String answer ="";
    private TTAdNative mTTAdNative;
    private String function_tabs="";
    //看视频
    private TTRewardVideoAd mRewardVideoAd;
    private boolean videoPrepare = false;
    @Override
    public void init(Bundle savedInstanceState) {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.news_activity_challenge);
        dataBinding.setLifecycleOwner(this);
        dataBinding.setViewModel(mViewModel);
        function_tabs = AppContext.getInstance().getAppPreferenceForever().getMainTabs()+"";
        UIUtils.setKeyEveryDayCoin(CoinTypeEnum.TZ_COIN);
        initViewData();
        initClink();
        Bundle bundle = getIntent().getExtras();
        if(!UIUtils.isEmpty(bundle)){
            try {
                nowZL = Integer.parseInt(bundle.getString("zl_num"));
                challengeNumber= Integer.parseInt(bundle.getString("zl_times"));
            }catch (Exception e){}
        }
        dataBinding.tvZl.setText(""+nowZL);
        getViewData();
        initCSJAD();
    }

    private void getViewData(){
        //获取广告
        CSJADTools.loadCSJAdMiddleBanner(getContext(),dataBinding.rlAdBottom,"",CSJ_BANNER_ONE_ID,375,90);
        GDTADTools.loadHFAd(getContext(),dataBinding.flAdBottomGdt,375,0 );
        if(challengeNumber>0){
            dataBinding.tvChallengeNum.setText(challengeNumber+"");
            dataBinding.tvSubmit.setVisibility(View.VISIBLE);
            if(function_tabs.contains("广告") && challengeNumber<30 && challengeNumber%3==2){
                dataBinding.tvSubmitVideo.setVisibility(View.VISIBLE);
            }else {
                dataBinding.tvSubmitVideo.setVisibility(View.GONE);
            }
            mViewModel.getData();
        }else {
            ToastUtil.show("今日挑战次数已用完");
            dataBinding.rlQuestion.setVisibility(View.GONE);
            dataBinding.tvSubmit.setVisibility(View.GONE);
        }
    }

    private void initViewData(){
        ActivityUtil.getInstance().showStatusView(this,dataBinding.viewSysTop,true);
        dataBinding.bindTransparentToolBar.toolBarTvTitle.setText("战力挑战");


        mViewModel.dataXZTBean.observe(this,dataBean->{
            if(!UIUtils.isEmpty(dataBean)){
                initSelect();

                setTextViewShow(dataBinding.layoutXzt.llXzt1,dataBinding.layoutXzt.tvXzt1,"A：",dataBean.getAnswerA());
                setTextViewShow(dataBinding.layoutXzt.llXzt2,dataBinding.layoutXzt.tvXzt2,"B：",dataBean.getAnswerB());
                setTextViewShow(dataBinding.layoutXzt.llXzt3,dataBinding.layoutXzt.tvXzt3,"C：",dataBean.getAnswerC());
                setTextViewShow(dataBinding.layoutXzt.llXzt4,dataBinding.layoutXzt.tvXzt4,"D：",dataBean.getAnswerD());

                reason = dataBean.getAnalytic();
                answer = dataBean.getAnswer();
                dataBinding.layoutXzt.tvXztTitle.setText(""+dataBean.getTitle());
                showUiBuyUrl();
            }
        });

        mViewModel.dataPDTBean.observe(this,dataBean->{
            if(!UIUtils.isEmpty(dataBean)){
                initPDSelect();
                pdtAnswer = dataBean.getAnswer()+"";
                reason = "";
                answer = dataBean.getAnalyse();
                dataBinding.layoutPdt.tvPdtTitle.setText(""+dataBean.getTitle());
                showUiBuyUrl();
            }
        });

        //更新挑战数据
        mViewModel.cBean.observe(this,cBean->{
            if(!UIUtils.isEmpty(cBean)){
                dataBinding.tvZl.setText(cBean.getNum()+"");
                dataBinding.tvChallengeNum.setText(cBean.getSurplusNum()+"");
                challengeNumber = cBean.getSurplusNum();
            }
        });
    }


    //根据请求结果展示ui
    private void showUiBuyUrl(){
        dataBinding.layoutXzt.llXzt.setVisibility(View.GONE);
        dataBinding.layoutPdt.llPdt.setVisibility(View.GONE);
        switch (mViewModel.url){
            case NEWS_KNOWLEDGE_WORK_WD:
                dataBinding.layoutXzt.llXzt.setVisibility(View.VISIBLE);
                break;
            case NEWS_KNOWLEDGE_WORK_PD:
                dataBinding.layoutPdt.llPdt.setVisibility(View.VISIBLE);
                break;
        }
    }

    //根据文字判断是否显示
    private void setTextViewShow(LinearLayout layout,TextView textView, String tabText, String value){
        if(UIUtils.isEmpty(value)){
            layout.setVisibility(View.GONE);
        }else {
            textView.setText(tabText+value);
        }
    }


    //重置选择题
    private void initSelect(){
        //选择
        dataBinding.layoutXzt.ivXzt1.setImageResource(R.drawable.img_item_unchoose);
        dataBinding.layoutXzt.ivXzt2.setImageResource(R.drawable.img_item_unchoose);
        dataBinding.layoutXzt.ivXzt3.setImageResource(R.drawable.img_item_unchoose);
        dataBinding.layoutXzt.ivXzt4.setImageResource(R.drawable.img_item_unchoose);
    }

    //重置判断
    private void initPDSelect(){
        dataBinding.layoutPdt.ivPdt1.setImageResource(R.drawable.img_item_unchoose);
        dataBinding.layoutPdt.ivPdt2.setImageResource(R.drawable.img_item_unchoose);
    }



    private void initClink(){
        dataBinding.bindTransparentToolBar.toolBarIvBack.setOnClickListener(v -> { finish(); });

        //选择题
        dataBinding.layoutXzt.llXzt1.setOnClickListener(v -> {
            initSelect();
            xztSelectText = "A";
            dataBinding.layoutXzt.ivXzt1.setImageResource(R.drawable.img_item_choosed);
        });
        dataBinding.layoutXzt.llXzt2.setOnClickListener(v -> {
            initSelect();
            xztSelectText = "B";
            dataBinding.layoutXzt.ivXzt2.setImageResource(R.drawable.img_item_choosed);
        });
        dataBinding.layoutXzt.llXzt3.setOnClickListener(v -> {
            initSelect();
            xztSelectText = "C";
            dataBinding.layoutXzt.ivXzt3.setImageResource(R.drawable.img_item_choosed);
        });
        dataBinding.layoutXzt.llXzt4.setOnClickListener(v -> {
            initSelect();
            xztSelectText = "D";
            dataBinding.layoutXzt.ivXzt4.setImageResource(R.drawable.img_item_choosed);
        });

        //判断题
        dataBinding.layoutPdt.llPdt1.setOnClickListener(v -> {
            initPDSelect();
            pdtSelect = "1";
            dataBinding.layoutPdt.ivPdt1.setImageResource(R.drawable.img_item_choosed);
        });
        dataBinding.layoutPdt.llPdt2.setOnClickListener(v -> {
            initPDSelect();
            pdtSelect = "0";
            dataBinding.layoutPdt.ivPdt2.setImageResource(R.drawable.img_item_choosed);
        });

        //提交
        dataBinding.tvSubmit.setOnClickListener(v ->delResult());

        //看视频
        dataBinding.tvSubmitVideo.setOnClickListener(v -> {

            if(UIUtils.isEmpty(pdtSelect) && UIUtils.isEmpty(xztSelectText)){
                ToastUtil.show("请选择");
                return;
            }
            if(UIUtils.isOpenAD()) prepareVideo();//准备视频播放
        });
    }

    //处理答案
    private void delResult(){
        switch (mViewModel.url){
            case NEWS_KNOWLEDGE_WORK_WD:
                if(UIUtils.isEmpty(xztSelectText)){
                    ToastUtil.show("请选择");
                }else {
                    if(!UIUtils.isEmpty(answer) && xztSelectText.equals(answer)){
                        mViewModel.notifyUserZL(0);
                        showResultDialog("挑战成功",answer,reason);
                    }else {
                        mViewModel.notifyUserZL(1);
                        showResultDialog("挑战失败",answer,reason);
                    }
                    dataBinding.tvSubmit.setVisibility(View.GONE);
                }
                break;
            case NEWS_KNOWLEDGE_WORK_PD:
                if(UIUtils.isEmpty(pdtSelect)){
                    ToastUtil.show("请选择");
                }else {
                    if(pdtAnswer.equals(pdtSelect)){
                        mViewModel.notifyUserZL(0);
                        showResultDialog("挑战成功",answer,reason);
                    }else {
                        mViewModel.notifyUserZL(1);
                        showResultDialog("挑战失败",answer,reason);
                    }
                    dataBinding.tvSubmit.setVisibility(View.GONE);
                }
                break;
        }
    }

    //展示失败弹框
    private void showResultDialog(String title,String answer,String reason){

        try {
            challengeResultDialog = new ChallengeResultDialog(getContext(),title,answer,reason,this::viewBtnClink);
            //显示窗口
            //设置layout在PopupWindow中显示的位置
            if(!UIUtils.isEmpty(dataBinding.llTop)){
                challengeResultDialog.showAtLocation(dataBinding.llTop, Gravity.CENTER, 0, 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 初始化穿山甲广告
     */
    private void initCSJAD(){
        try{
            TTAdManagerHolder.init(ChallengeActivity.this);
            mTTAdNative = TTAdManagerHolder.getTTAdNative(ChallengeActivity.this);
            mTTAdNative.loadRewardVideoAd(CSJADTools.getAdSlot("挑战奖励",1,"challenge"),
                    new TTAdNative.RewardVideoAdListener() {
                        @Override
                        public void onError(int i, String s) {
                            videoPrepare = false;
                        }

                        @Override
                        public void onRewardVideoAdLoad(TTRewardVideoAd ttRewardVideoAd) {
                            videoPrepare = false;
                            if(UIUtils.isEmpty(ttRewardVideoAd))return;
                            mRewardVideoAd = ttRewardVideoAd;
                        }

                        @Override
                        public void onRewardVideoCached() {
                            videoPrepare = true;
                        }
                    });

        }catch (Exception e){

        }
    }

    /**
     * 准备视频
     */
    private void prepareVideo(){
        if (mRewardVideoAd != null && videoPrepare) {
            mRewardVideoAd.setRewardAdInteractionListener(new TTRewardVideoAd.RewardAdInteractionListener() {

                @Override
                public void onAdShow() {
                    Log.d("VideoAd","onAdShow");
                    //   Toast.makeText(RewardVideoActivity.this, "rewardVideoAd show", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onAdVideoBarClick() {
                    Log.d("VideoAd","onAdVideoBarClick");
                    //  Toast.makeText(RewardVideoActivity.this, "rewardVideoAd bar click", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onAdClose() {
                    Log.d("VideoAd","onAdClose");
                    //   Toast.makeText(RewardVideoActivity.this, "rewardVideoAd close", Toast.LENGTH_SHORT).show();
                    mRewardVideoAd = null;
                    CustomCoinToast.showToast(ChallengeActivity.this,"挑战奖励","1金币");
                 //   ToastUtil.show("恭喜获得1金币奖励");
                    dataBinding.tvSubmitVideo.setVisibility(View.GONE);
                    delResult();
                  //  CustomCoinToast.showToast(ChallengeActivity.this,"挑战奖励","1金币");
                }

                @Override
                public void onVideoComplete() {
                    Log.d("VideoAd","onVideoComplete");
                    // Toast.makeText(RewardVideoActivity.this, "rewardVideoAd complete", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onVideoError() {
                    Log.d("VideoAd","onVideoError");
                }

                @Override
                public void onRewardVerify(boolean b, int i, String s, int i1, String s1) {

                }

//                @Override
//                public void onRewardVerify(boolean b, int i, String s, int i1, String s1) {
//                    Log.d("VideoAd","onRewardVerify"+s+"=="+s1);
//                }

                @Override
                public void onSkippedVideo() {
                    Log.d("VideoAd","onSkippedVideo");
                }
            });
            //展示广告，并传入广告展示的场景
            mRewardVideoAd.showRewardVideoAd(ChallengeActivity.this, TTAdConstant.RitScenes.CUSTOMIZE_SCENES, "scenes_test");
        } else {
            ToastUtil.show("视频资源准备中，请稍后再试");
        }
    }

    @Override
    public void viewBtnClink() {
        //刷新战力
        if(challengeNumber<1){
            ToastUtil.show("今日挑战次数已用完");
            dataBinding.rlQuestion.setVisibility(View.GONE);
            dataBinding.tvSubmit.setVisibility(View.GONE);
        }else {
            xztSelectText = "";
            pdtAnswer = "";
            pdtSelect = "";
            dataBinding.tvSubmit.setVisibility(View.VISIBLE);
        }
        getViewData();
    }
}
